package tptecnicas.printers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * Implementacion especifica de escritor de logs
 * en archivos locales. Define el metodo virtual del Template Method
 * asociado a la clase Writer.
 */
public class FileTargetWriter extends Writer {

	public FileTargetWriter(List<String> parameters) {
		super(parameters);
		
		// if file or directory doesnt exists, then create it
		File file = new File(this.path);
		try {
			File dir = new File(file.getParent());
			if (!dir.exists()) {
				dir.mkdir();
			}
			file.createNewFile();
		} catch (IOException e) {
			System.err.println("Caught IOException: " +  e.getMessage());
		}catch (Exception e){
			System.err.println("Caught Exception: " +  e.getMessage());
		}
	}
	
	public void writeOnOutput(String result) {
		if (result != null)	{
			File file = new File(this.path);
			FileWriter fw;
			BufferedWriter bw;
			try {
				fw = new FileWriter(file, true);
				bw = new BufferedWriter(fw);
				bw.write(result);
				bw.newLine();
				bw.close();
			} catch (IOException e) {
				// Unable to log message on file
				System.err.println("Caught IOException: " +  e.getMessage());
			}	
		}
	}
}
